import EventBus from "@/util/EventBus";
import {ref} from 'vue'


function _generateEndpoint() {
  let protocol
  if (window.location.protocol === 'https:') {
    protocol = 'wss://';
  } else {
    protocol = 'ws://';
  }
  return protocol + '127.0.0.1:8080/webssh';
}

const socket = ref(null)

const createWs = () => {
  const _socket = new WebSocket(_generateEndpoint());
  _socket.onopen = () => {
    EventBus.emit("", "\r\n 网络已连接连接")
    socket.value = _socket
    console.log(socket)
  }
  _socket.onmessage = evt => {
    const map = JSON.parse(evt.data)
    EventBus.emit(map.id, map.data.toString())
  }
  _socket.onclose = evt => {
    EventBus.emit("", "\r\nError 连接已断开")
    setTimeout(() => {
      createWs()
    })
  }
}

createWs()

export default socket